package cn.xiaohuodui.controller;

import cn.xiaohuodui.exceptions.BussException;
import cn.xiaohuodui.form.back.admin.*;
import cn.xiaohuodui.res.JsonRes;
import cn.xiaohuodui.service.AdminService;
import cn.xiaohuodui.utils.IpUtil;
import cn.xiaohuodui.utils.json.JsonUtil;
import cn.xiaohuodui.vo.admin.AdminVo;
import cn.xiaohuodui.vo.admin.PermissionVo;
import cn.xiaohuodui.vo.admin.RoleCheckVo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 管理员控制器
 *
 * @author keepcleargas
 * @create 2017-05-04 上午9:33
 */
@Controller
@RequestMapping("/admins")
public class AdminController {

    @Autowired
    private AdminService adminService;


    @GetMapping
    public String index(Model model) {
        return "admin/admin-list";
    }


    @GetMapping("/roles")
    public String roles(Model model) {
        List<RoleCheckVo> roleCheckVos = adminService.getAdminRoles(0);
        model.addAttribute("roles", roleCheckVos);
        return "admin/admin-role";
    }

    @RequestMapping("/page")
    @ResponseBody
    public String getPage(HttpServletRequest request) {
        String limitStr = request.getParameter("length");

        int limit = limitStr == null ? 10 : Integer.parseInt(limitStr);

        String offsetStr = request.getParameter("start");
        int offset = offsetStr == null ? 0 : Integer.parseInt(offsetStr);

        String drawStr = request.getParameter("draw");
        int draw = drawStr == null ? 0 : Integer.parseInt(drawStr);

        String userName = request.getParameter("username");

        AdminBackQueryForm form = new AdminBackQueryForm();
//        form.setLimit(limit);
//        form.setOffset(offset);
//        form.setUsername(userName);
//
//        int count = adminService.backCount(form);
//        List<AdminBackDo> datas = adminService.backQeury(form);

        Map<String, Object> results = new HashMap<>();
        results.put("draw", draw);
//        results.put("data", datas);
//        results.put("recordsFiltered", count);
//        results.put("recordsTotal", count);

        return JsonUtil.seriazileAsStringWithNull(results);
    }

    /**
     * 获取管理员权限组
     *
     * @param adminId
     * @return
     */
    @GetMapping("/adminRoles")
    @ResponseBody
    public String adminRoles(@RequestParam(value = "adminId", defaultValue = "0") int adminId) {
        List<RoleCheckVo> roles = adminService.getAdminRoles(adminId);
        return JsonUtil.seriazileAsStringWithNull(roles);
    }

    /**
     * 获取权限组的 权限列表
     *
     * @param roleId
     * @return
     */
    @GetMapping("/rolePermissions")
    @ResponseBody
    public String RolePermissions(@RequestParam(value = "roleId", defaultValue = "0") int roleId) {
        List<PermissionVo> roles = adminService.getRolePermissions(roleId);
        return JsonUtil.seriazileAsStringWithNull(roles);
    }

    /**
     * 获取权限组的 权限列表
     *
     * @param roleId
     * @return
     */
    @DeleteMapping("/roles/{roleId}")
    @ResponseBody
    public JsonRes deleteRole(@PathVariable(value = "roleId") int roleId) {
        adminService.deleteRole(roleId);
        return JsonRes.success();
    }

    /**
     * 获取权限组的 权限列表
     *
     * @param roleId
     * @return
     */
    @PostMapping("/rolePermissions")
    @ResponseBody
    public JsonRes RolePermissions(@RequestParam(value = "roleId", defaultValue = "0") int roleId
            , String role, String description, String pids) {
        adminService.updateRolePermissions(roleId, role, description, pids);
        return JsonRes.success();
    }

    /**
     * 更改管理员权限组
     *
     * @param adminId
     * @param roles
     * @return
     */
    @PostMapping("/adminRoles")
    @ResponseBody
    public JsonRes updateAdminRoles(@RequestParam("adminId") int adminId, @RequestParam("roleIds") String roles) {
        adminService.updateAdminRoles(adminId, roles);
        return JsonRes.success();
    }


    @PostMapping
    @ResponseBody
    public JsonRes save(@ModelAttribute AdminBackForm form) throws BussException {
        adminService.save(form);
        return JsonRes.success();
    }


    @DeleteMapping("/{id}")
    @ResponseBody
    public JsonRes remove(@PathVariable("id") Integer id) {
        adminService.remove(id);
        return JsonRes.success();
    }


    @PutMapping("/{id}")
    @ResponseBody
    public JsonRes update(@ModelAttribute AdminBackForm form, @PathVariable("id") Integer id) throws BussException {
        form.setId(id);
        adminService.update(form);
        return JsonRes.success();
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public
    @ResponseBody
    JsonRes login(@ModelAttribute BAdminLoginForm loginForm, HttpServletRequest request, HttpServletResponse response) throws BussException {
        try {
            UsernamePasswordToken token = new UsernamePasswordToken(loginForm.getUsername(), loginForm.getPassword());
            SecurityUtils.getSubject().login(token);

            Subject currentUser = SecurityUtils.getSubject();
            AdminVo adminVo = (AdminVo) currentUser.getPrincipal();
            //更新最后一次登录信息
            loginForm.setUid(adminVo.getId());
            loginForm.setIp(IpUtil.getIpAddr(request));
            loginForm.setAgent(request.getHeader("User-Agent"));
            adminService.updateLastLogin(loginForm);
        } catch (Exception e) {
            e.printStackTrace();
//            return new JsonRes(100, "帐号不正确/密码不正确");
        }
        return JsonRes.success();
    }

    /**
     * 密码修改
     *
     * @param resetForm
     * @param uid
     * @return
     * @throws BussException
     */
    @RequestMapping(value = "/reset", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public
    @ResponseBody
    JsonRes resetPwd(@ModelAttribute BAdminResetForm resetForm, @RequestParam("uid") int uid) throws BussException {
        resetForm.setUid(uid);
        adminService.updatePwd(resetForm);
        return JsonRes.success();
    }

//    @RequestMapping(value = "/logout", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
//    public
//    @ResponseBody
//    JsonRes logout(HttpServletRequest request, HttpServletResponse response) {
//        HttpSession session = request.getSession();
//        session.setAttribute(ApplicationConstants.SIGN_IN_USER, null);
//        Cookie[] cookies = request.getCookies();
//        Arrays.stream(cookies)
//                .filter(cookie -> cookie.getName().equals("username") || cookie.getName().equals("password"))
//                .forEach(cookie -> {
//                    cookie.setMaxAge(0);
//                    response.addCookie(cookie);
//                });
//        return JsonRes.success();
//    }
}
